<template>
    <div>
        <div style="backgroud:#fff">
            <el-form :inline="true" :model="formInline">
                <el-form-item label="关键字" style="width:30%">
                    <el-input
                              v-model="sysUserSearchDto.keyword"
                              placeholder="用户名、姓名、手机号码"
                              />
                </el-form-item>
                <el-form-item label="创建时间" style="width:50%">
                    <el-date-picker
                                    v-model="dates"
                                    type="daterange"
                                    :clearable="false"
                                    unlink-panels
                                    range-separator="To"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    :shortcuts="shortcuts"
                                    size="default"
                                    value-format="YYYY-MM-DD"
                                    />
                </el-form-item>
            </el-form>

            <el-form-item>
                <el-button type="primary" size="small" @click="initData">
                    搜索
                </el-button>
                <el-button size="small" @click="reset">重置</el-button>
            </el-form-item>
            <div>
                <el-button type="success" size="small" @click="showDialog()">
                    添加
                </el-button>
            </div>
        
        </div>

        <el-table :data="users" stripe style="width: 100%">
            <el-table-column prop="username" label="用户名" width="180" />
            <el-table-column prop="name" label="姓名" width="180" />
            <el-table-column prop="phone" label="手机" />
            <el-table-column prop="avatar" label="头像">
                 <template #default="scope">
                    <img :src="scope.row.avatar" style="width:50px;height:50px" />
                </template>
            </el-table-column>

            <el-table-column prop="description" label="描述" width="100" />
            <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                    {{ +scope.row.status === 0 ? '禁用' : '正常' }}
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />

            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="edit( scope.row)">
                        修改
                    </el-button>
                    <el-button
                               size="small"
                               type="danger"
                               @click="deletes(scope.row)"
                               >
                        删除
                    </el-button>
                    <el-button
                               size="small"
                               type="warning"
                               @click="showAssignRolesDialog(scope.row)"
                               >
                        分配角色
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div style="margin-top:50px">
            <el-pagination
                           v-model:current-page="pageNum"
                           v-model:page-size="pageSize"
                           :page-sizes="[1, 2, 3, 4]"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="total"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           />
        </div>
        <div>
            <el-dialog v-model="dialogFormVisible" :title="title">
                <el-form>
                    <el-form-item label="用户名" :label-width="formLabelWidth">
                        <el-input v-model="sysUser.username" autocomplete="off" />
                    </el-form-item>
                    <el-form-item
                                  v-if="!sysUser.id"
                                  label="密码"
                                  :label-width="formLabelWidth"
                                  >
                        <el-input v-model="sysUser.password" autocomplete="off" />
                    </el-form-item>

                    <el-form-item label="用户头像" :label-width="formLabelWidth">
    <el-upload
               class="avatar-uploader"
               :action="uploadUrl"
               :show-file-list="false"
               :headers="headers"
               name="file"
               :on-success="handleAvatarSuccess"
               :on-error="handleAvatarError"
               >
        <img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
</el-form-item>

                    <el-form-item label="姓名" :label-width="formLabelWidth">
                        <el-input v-model="sysUser.name" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="手机" :label-width="formLabelWidth">
                        <el-input v-model="sysUser.phone" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="描述" :label-width="formLabelWidth">
                        <el-input v-model="sysUser.description" autocomplete="off" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="addOrUpdate">
                            提交
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
        <div>
              <el-dialog v-model="dialogAssignRoleVisible" title="分配角色">
                <el-form>
                  <el-form-item label="用户名" :label-width="formLabelWidth">
                    <el-input v-model="sysUser.username" autocomplete="off" disabled />
                  </el-form-item>
                  <el-form-item label="角色列表" :label-width="formLabelWidth">
                    <el-checkbox-group v-model="checkedRoleIds" size="small">
                      <el-checkbox
                        v-for="role in roles"
                        :key="role.id"
                        :label="role.id"
                        :checked="role.checked"
                      >
                        {{ role.roleName }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-form>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="dialogAssignRoleVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleAssignRoles">
                      提交
                    </el-button>
                  </span>
                </template>
              </el-dialog>
        </div>
    </div>
</template>
<script setup>
    import { ref,onMounted } from 'vue'
    import {selectUsers,addUser,deleteUser,updateUser,assignRoles2User} from '@/api/sysUser'
    import { ElMessage,ElMessageBox } from 'element-plus'
    import { useApp } from '@/pinia/modules/app'
    import { getAllRoles } from '@/api/sysRole'
    const dialogAssignRoleVisible = ref(false)
    const checkedRoleIds = ref([])
    const roles = ref([])
    const showAssignRolesDialog = async(row) => {
        checkedRoleIds.value=[]
        roles.value=[]
        sysUser.value=row
        const{data}=await getAllRoles(row.id)
        roles.value=data
        dialogAssignRoleVisible.value = true
    }
    const handleAssignRoles = async () => {
    await assignRoles2User(sysUser.value.id,checkedRoleIds.value)
    ElMessage.success('角色分配成功')
    dialogAssignRoleVisible.value = false
    }



    const uploadUrl = ref('http://127.0.0.1:8081/admin/system/file/upload/avatar')
const { authorization } = useApp()
const headers = { token: authorization.token }
const handleAvatarSuccess = (response, uploadFile) => {
    if (+response.code === 200) {      
        sysUser.value.avatar = response.data
        ElMessage.success('上传成功')
    } else {
        ElMessage.error(response.message)
    }
}

const handleAvatarError = (error, uploadFile) => {
    ElMessage.error('网络连接失败')
}
    

    const sysUserSearchDto = ref({})
    let dates=ref([])
    //分页导航的属性和函数
    const pageNum = ref(1)
    const pageSize = ref(3)
    const total = ref(30)
    let reset = () => {
        pageNum.value = 1
        pageSize.value = 3
        sysUserSearchDto.value = {}
        dates.value=[]
        initData()
    }
    const handleSizeChange = (val) => {
        pageSize.value=val
        initData()

    }
    const handleCurrentChange = (val) => {
        pageNum.value=val
        initData()
    }
    const users = ref([])

onMounted(()=>{
    initData()
})
let initData=async()=>{
    if(dates.value&&dates.value.length==2){
        sysUserSearchDto.value.start=dates.value[0]
        sysUserSearchDto.value.end=dates.value[1]
    }

   let {data,code,message}=await selectUsers(pageNum.value,pageSize.value,sysUserSearchDto.value)
         total.value=data.total
         users.value=data.list
}

let dialogFormVisible=ref(false)
let sysUser=ref({})
let title = ref('')
let showDialog=()=>{
    title.value = '添加角色'
    sysUser.value={}
    dialogFormVisible.value=true

}

let add=async()=>{
    await addUser(sysUser.value)
    ElMessage.success('添加成功')
    dialogFormVisible.value=false
    initData()
}

let edit=async(row)=>{
    
    sysUser.value=row
    title.value='更新角色'
    dialogFormVisible.value=true
}
let update=async()=>{
await updateUser(sysUser.value)
ElMessage.success('更新成功')
dialogFormVisible.value=false

}

let addOrUpdate=()=>{
    if(sysUser.value.id){
        update()
    }else{
        add()
    }

}

let deletes=(row)=>{
    ElMessageBox.confirm(
    '确定删除该角色吗？',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
        await deleteUser(row.id)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      initData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//日期选择器快速选择时  计算时间日期范围的
const shortcuts = [
        {
            text: 'Last week',
            value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                return [start, end]
            },
        },
        {
            text: 'Last month',
            value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                return [start, end]
            },
        },
        {
            text: 'Last 3 months',
            value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                return [start, end]
            },
        },
    ]

</script>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>